package com.acmedcare.framework.exchange.center.core.handler;

import com.acmedcare.framework.exchange.center.core.Const;
import com.acmedcare.framework.exchange.center.core.PluginContainerMBean;
import com.acmedcare.framework.exchange.center.core.PluginMetadata;
import com.acmedcare.framework.exchange.center.core.agent.AgentMetadata;
import com.acmedcare.framework.exchange.center.core.metadata.AgentContext;
import com.acmedcare.framework.exchange.center.core.metadata.IDataAgent;
import com.acmedcare.framework.exchange.center.entity.bean.Task;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SuppressWarnings("unused")
public class AgentHandler implements AgentHandlerMBean {

  final PluginContainerMBean pluginContainer;
  final ObjectMapper objectMapper;
  final IAgentPublisher agentPublisher;

  public AgentHandler(
      PluginContainerMBean pluginContainer, ObjectMapper objectMapper,
      IAgentPublisher agentPublisher) {
    this.pluginContainer = pluginContainer;
    this.objectMapper = objectMapper;
    this.agentPublisher = agentPublisher;
  }

  @Override
  public void invoke(Task task) {

    try {

      PluginMetadata metadata = pluginContainer.getPlugin(task.getPluginName());
      AgentMetadata agentMetadata = metadata.getAgentMap().get(task.getAgentName().toLowerCase());
      if (agentMetadata == null) {

        log.error("尚未找到采集器，请确认采集器是否已经加载!");
        return;
      }

      IDataAgent dataAgent;
      if (agentMetadata.getInstance() == null) {

        dataAgent = (IDataAgent) agentMetadata.getAgentClass().newInstance();
        agentMetadata.setInstance(dataAgent);
      } else {

        dataAgent = agentMetadata.getInstance();
      }

      List<?> data = dataAgent.doWork(new AgentContext());

      log.info("获取到插件数据:");
      if (data != null && agentPublisher != null && !data.isEmpty()) {

        data.forEach(obj -> agentPublisher.publish(Const.TaskExchangePrefix + task.getName(), obj));
      }
    } catch (Exception e) {

      log.error("执行数据采集器发生错误！", e);
    }
  }
}
